<template>
    <el-select v-bind="$attrs" v-on="$listeners" clearable @clear="clearSelect" @focus="focusSelect"   v-model="value1"  :loading="selectLoading">
        <el-option :label="item[labelKey]" :value="item[valueKey]+''" v-for="item in options" :key="item[valueKey]" /></el-select>
</template>

<script>
export default {
  props: {
    action: {
      type: Function
    },
    actionQuery: {
      type: Object,
      default: () => {
        return {}
      }
    },
    changeQuery: String,
    labelKey: {
      type: String,
      default: 'name'
    },
    valueKey: {
      type: String,
      default: 'value'
    },
    dictKey: String,
    value: [String, Number, Array],
    option: [Array, Object]
  },
  data () {
    return {
      options: [],
      value1: '',
      currentData: {},
      selectLoading: false
    }
  },
  watch: {
    async option (val) {
      if (val) {
        this.options = val
      }
    },
    value (val) {
      //    console.log('下拉组件中的val', val)
      if (val) {
        if (this.value1 !== val) {
          this.value1 = val
        }
      }
    },
    value1 (val) {
      //    console.log('下拉组件中的val1', val, this.options)
      if ((val !== undefined || val !== null) && this.options) {
        if (this.options.length !== 0) {
          this.$emit(
            'change-data',
            val,
            this.options.find(e => e[this.valueKey] === val)
          )
        }
      } else {
        console.log('参数值为null')
      }
    },
    dictKey (val) {
      this.fetchOptions()
    },
    changeQuery (val) {
      this.fetchOptions()
    },
    options () {
    }
  },
  methods: {
    async fetchOptions () {
      this.selectLoading = true
      if (this.dictKey) {
        this.options = await this.$request.get('/Home/Region/getRegionList', {
          params: {
            pId: this.dictKey
          }
        })
        this.$emit('after-action', this.options)
        this.selectLoading = false
      } else if (this.action) {
        const options = await this.action(this.actionQuery).catch(() => {
          this.selectLoading = false
          return false
        })
        if (options.data) {
          if (options.data.length === 0) {
            this.options = []
          } else {
            this.options = options.data
          }
        } else {
          this.options = options
        }
        this.$emit('after-action', this.options)
        this.selectLoading = false
      }
    },
    clearSelect () {
      this.value1 = ''
      this.$emit('change-data', this.value1)
      this.$emit('clear-data')
    },
    focusSelect (val) {
      if (val.srcElement.value === '') {
        this.$emit('change-data', val.srcElement.value)
      }
    }
  },
  async created () {
    if (this.value) {
      this.value1 = this.value
    }
    this.fetchOptions()
  }
}
</script>

<style scoped>

</style>
